﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NHibernate.Criterion;
using ZDSoft.QLMS.Entity.TestOnline;
using ZDSoft.QLMS.Web.Helpers;
using ZDSoft.QLMS.Entity;
using ZDSoft.QLMS.Entity.QuestionLibrary;
using ZDSoft.QLMS.Entity.SystemSetting;
using ZDSoft.QLMS.Component.SystemSettingComponent;

namespace ZDSoft.QLMS.Web.Controllers
{
    public class TestController : Controller
    {
        public ActionResult StudentLogin(string userCode,string password)
        {
            return View();
        }

        public ActionResult PrepareTest()
        {
            return View();
        }

        public ActionResult Testing()
        {
            TempData["Now"] = DateTime.Now.ToString();
            return View();
        }

        [HttpGet]
        public string GetCourse(int id)
        {
            return new Course().FindByID(id).Name;
        }

        public string GetTest()
        {
            string result = "{";
            Organization org = AppHelper.LoginedUser.Organization;
            IList<Test> tests = new Test().FindAll();
            foreach (Test test in tests)
            {
                foreach (Organization i in test.Organizations)
                {
                    if (i.ID == org.ID)
                    {
                        result += "\"courseID\":\"" + test.Course.ID + "\",\"course\":\"" + test.Course.Name + "\",\"score\":\"" + test.TestPaper.score + "\",\"time\":\"" + test.TestPaper.Min + "\",\"testPaperID\":\"" + test.TestPaper.ID + "\",\"testID\":\"" + test.ID + "\"";
                    }
                }
            }
            result += "}";
            return result;
        }

        public string StudentTest(int loginCode, string password, string validateCode)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            queryConditions.Add(Expression.Eq("ID", loginCode));
            queryConditions.Add(Expression.Eq("Password", password));
            IList<User> users = new User().Find(queryConditions);
            if (users.Count != 0)
            {
                if (validateCode == Session["ValidateCode"].ToString())
                {
                    AppHelper.LoginedUser = users[0];
                    IList<Role> roles = users[0].Roles;
                    IList<SystemFunction> systemFunctions = new List<SystemFunction>();
                    foreach (Role role in roles)
                    {
                        foreach (SystemFunction systemFunction in role.SystemFunctions)
                        {
                            systemFunctions.Add(systemFunction);
                        }
                    }
                    AppHelper.Privileges = systemFunctions;
                    return "success";
                }
                else
                {
                    return "验证码错误！";
                }
            }
            else
            {
                return "用户名或密码错误或该用户名暂未激活！";
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        public ActionResult Update()
        {
            return View();
        }

        public string GetTestByID(int id)
        {
            Test test = new Test().FindByID(id);
            IList<Course> courses = new Course().FindAll();
            string result = "{";
            result += "\"date\":\"" + test.Date + "\",";
            result += "\"id\":\"" + test.ID + "\",";
            result += "\"courseID\":\"" + test.Course.ID + "\",";
            result += "\"testpaperID\":\"" + test.TestPaper.ID + "\",";
            result += "\"isactive\":\"" + test.IsActive + "\"";
            result += "}";
            return result;
        }

        public JsonResult GetClassByTestPaper(int id)
        {
            IList<Organization> testOrg = new Test().FindByID(id).Organizations;
            IList<Organization> organizations = new Organization().FindAll();
            IList<Organization> tmpOrg = new List<Organization>();
            foreach (Organization i in organizations)
            {
                if (i.Children == null || i.Children.Count == 0)
                {
                    tmpOrg.Add(i);
                }
            }
            IList<ZTreeHelper<Organization>.ZTreeNode> tree = new List<ZTreeHelper<Organization>.ZTreeNode>();
            foreach (Organization i in tmpOrg)
            {
                bool flag = false;
                foreach (Organization j in testOrg)
                {
                    if (i.ID == j.ID)
                    {
                        flag = true;
                        ZTreeHelper<Organization>.ZTreeNode node = new ZTreeHelper<Organization>.ZTreeNode();
                        node.id = i.ID;
                        node.name = i.OrganizationName;
                        node.@checked = true;
                        tree.Add(node);
                        break;
                    }
                }
                if (!flag)
                {
                    ZTreeHelper<Organization>.ZTreeNode node = new ZTreeHelper<Organization>.ZTreeNode();
                    node.id = i.ID;
                    node.name = i.OrganizationName;
                    tree.Add(node);
                }
            }
            return this.Json(tree, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public void Create(string selectIDs, int courseID, DateTime date, int testpaper, string IsActive)
        {
            Test test = new Test();
            test.Course = new Course().FindByID(courseID);
            test.Date = date;
            test.TestPaper = new TestPaper().FindByID(testpaper);
            test.IsActive = bool.Parse(IsActive);
            test.Organizations = new List<Organization>();
            IList<string> arr =selectIDs.Split(',');
            foreach (string i in arr)
            {
                test.Organizations.Add(new Organization().FindByID(int.Parse(i)));
            }
            test.Create();
        }

        public JsonResult GetClass()
        {
            IList<Organization> organizations = new Organization().FindAll();
            IList<Organization> tmpOrg = new List<Organization>();
            foreach (Organization i in organizations)
            {
                if (i.Children == null || i.Children.Count==0) 
                {
                    tmpOrg.Add(i);
                }
            }
            IList<ZTreeHelper<Organization>.ZTreeNode> tree = new List<ZTreeHelper<Organization>.ZTreeNode>();
            foreach (Organization i in tmpOrg)
            {
                ZTreeHelper<Organization>.ZTreeNode node = new ZTreeHelper<Organization>.ZTreeNode();
                node.id = i.ID;
                node.name = i.OrganizationName;
                tree.Add(node);
            }
            return this.Json(tree, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public void Update(string selectIDs, int testID, int courseID, DateTime date, int testpaper, string IsActive)
        {
            Test test = new Test().FindByID(testID);
            test.Course = new Course().FindByID(courseID);
            test.Date = date;
            test.TestPaper = new TestPaper().FindByID(testpaper);
            test.IsActive = bool.Parse(IsActive);
            test.Organizations = null;
            test.Organizations = new List<Organization>();
            IList<string> arr = selectIDs.Split(',');
            foreach (string i in arr)
            {
                test.Organizations.Add(new Organization().FindByID(int.Parse(i)));
            }
            test.Update();
        }

        public void Withdraw(int id)
        {
            Test test = new Test().FindByID(id);
            if (test.IsActive)
            {
                test.IsActive = false;
            }
            else
            {
                test.IsActive = true;
            }
            test.Update();
        }

        public string GetCourse()
        {
            string result = "";
            IList<Course> courses = new Course().FindAll();
            foreach (Course i in courses)
            {
                result += i.ID + "," + i.Name + "|";
            }
            result = result.Substring(0, result.Length - 1);
            return result;
        }

        public string GetTestPaper(int courseID)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            queryConditions.Add(Expression.Eq("Course", new Course().FindByID(courseID)));
            IList<TestPaper> testPapers = new TestPaper().Find(queryConditions);
            string result = "";
            if (testPapers.Count != 0)
            {
                foreach (TestPaper i in testPapers)
                {
                    result += i.ID + "," + i.Name + "|";
                }
                result = result.Substring(0, result.Length - 1);
                return result;
            }
            else
            {
                return null;
            }
        }

        public string GetPaged(int pageIndex, int pageSize, string strSearchProperty,
            string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }
            int count;
            int pageNum;

            IList<Test> list = new List<Test>();
            IList<Test> tests = new Test().GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);

            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }
            if (tests.Count != 0 && tests != null)
            {
                string jsonStr = "[";
                foreach (Test t in tests)
                {
                    jsonStr += "{\"ID\":\"" + t.ID + "\",\"Date\":\"" + t.Date + "\",\"Course\":\"" + t.Course.Name + "\",\"TestPaper\":\"" + t.TestPaper.Name + "\",\"IsActive\":\"" + t.IsActive + "\"},";
                }
                jsonStr += "{\"ID\":\"" + pageNum + "\"}";
                jsonStr += "]";
                return jsonStr;
            }
            else
            {
                return null;
            }
        }

        public string GetTestPaperByID(int id)
        {
            TestPaper tp = new TestPaper().FindByID(id);
            string result = "[";
            foreach (TestPaperPart tpp in tp.TestPaperParts)
            {
                result += "{\"name\":\"" + tpp.Type.Name + "\",\"score\":\"" + tpp.score + "\",\"chi\":[";
                foreach (TestPaperMinPart tmp in tpp.TestPaperMinParts)
                {
                    foreach (Question q in tmp.Questions)
                    {
                        result += "{\"id\":\""+q.ID+"\",\"name\":\"" + q.Title + "\",\"chi\":[";
                        foreach (Answer a in q.Answers)
                        {
                            result += "{\"id\":\"" + a.ID + "\",\"score\":\"" + tmp.score / tmp.Questions.Count + "\",\"index\":\"" + a.SerialNumber + "\",\"content\":\"" + a.Content + "\",\"isTrue\":\"" + a.IsCorrect + "\"},";
                        }
                        result = result.Substring(0, result.Length - 1);
                        result+="]},";
                    }
                }
                result = result.Substring(0, result.Length - 1);
                result += "]},";
            }
            result = result.Substring(0, result.Length - 1);
            result += "]";
            return result;
        }

        public void CreateScore(float score, int testID)
        {
            Score entity = new Score();
            entity.Value = score;
            entity.User = AppHelper.LoginedUser;
            entity.Test = new Test().FindByID(testID);
            entity.Create();
        }
    }
}
